<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/6
 * Time: 14:50
 */


namespace app\home\controller;


use app\common\model\Config;
use app\common\model\Level;
use app\common\model\PayAmount;
use app\common\model\Poster;
use app\common\model\RollMessage;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;
use think\Request;


class Publice
{
    /**
     *  获取省
     */
    public function getProvince()
    {
        /*    $model = new Province();
             $data = $model->select()->toArray();*/

        ;
        return success('省数据', config('city.province'));
    }

    /**
     * 市数据
     */
    public function getCity(Request $request)
    {

        $param = $request->param();
        if (isset($param['parent_id']) && !empty($param['parent_id'])) {
            $city = config('city.city');
            foreach ( $city as $value){
                if ($value['parent_id'] == $param['parent_id']){
                    $data[] = $value;
                }
            }
            return success('市数据', $data);
        } else {
            return success('省数据', config('city.city'));
        }
        //return success('市数据', $data);
    }

    /**
     * 获取区数据
     */
    public function getArea(Request $request)
    {

        $param = $request->param();
        if (isset($param['parent_id']) && !empty($param['parent_id'])) {
            $city =  config('city.county');
            foreach ( $city as $value){
                if ($value['parent_id'] == $param['parent_id']){
                    $data[] = $value;
                }
            }
            return success('区数据', $data);
        }

        return success('区数据', config('city.county'));
    }

    /**
     * 海报图
     */
    public function poster(Request $request)
    {
        $model = new Poster();
        $param = $request->param();
        $where['type'] = 1;
        if (isset($param['type']) && !empty($param['type'])) {
            $where['type'] = $param['type'];
        }
        $data = $model->where($where)->order('sort', 'desc')->select();
        return success('海报轮播图', $data);
    }


    public function userLevel(Request $request)
    {
        $levelModel = new Level();
        $data = $levelModel->order('level', 'asc') ->where('level','>',0)->where(['status' => 1])->select();
        return success('用户等级', $data);

    }

    public function getConfig(Request $request)
    {
        $configModel = new Config();
        $data = $configModel->select() ->toArray();
        $data = array_column($data, 'value', 'key');
        return success('配置', $data);
    }


    public function upload(Request $request)
    {

        $configModel = new Config();
        $value = $configModel::getConfigValue('upload_way');
        $files = $request->file("file");
        if (!$files){
            return error('请上传文件');
        }
        $ext = $files->extension();

        $size = filesize($files);

        if ($value == 1) {
            try {
                $path = 'uploads';
                // 将图片保存至本地
                $saveName = Filesystem::disk('public')->putFile($path, $files);
                $saveName = $request->domain() . '/storage/' . $saveName;
                return success('上传成功', ['url' => $saveName]);
                //将文件上传的路径返回
            } catch (\think\exception\ValidateException $e) {
                return error($e->getMessage());
            }
        } else if ($value == 2) {
            $fileType = $configModel::getConfigValue('qiniu_file_type');
            if ($fileType){
                $fileTypeArray = explode(',',$fileType);
                if (!in_array($ext,$fileTypeArray)){
                    return error('此类型文件不允许上传');
                }
            }

            $qiniu_access_key = $configModel::getConfigValue('qiniu_access_key');
            $qiuniu_secret_bucket = $configModel::getConfigValue('qiniu_secret_key');
            $qiniu_bucket = $configModel::getConfigValue('qiniu_bucket');

            // 构建Auth对象
            $auth = new Auth($qiniu_access_key, $qiuniu_secret_bucket);

            // 要上传的空间
            $bucket = $qiniu_bucket;
            // 生成上传Token
            $token = $auth->uploadToken($bucket);
            // 上传到七牛后的文件名
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();

            // 初始化UploadManager类
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $files->getRealPath());
            if ($err !== null) {
                return false;
            } else {
                return  success('上传成功',['url' => $configModel::getConfigValue('qiniu_domin') . '/'.$ret['key']]);
            }
        }else{
            $fileType = $configModel::getConfigValue('ali_file_type');
            $fileTypeArray = explode(',',$fileType);
            if (!in_array($ext,$fileTypeArray)){
                return error('此类型文件不允许上传');
            }
            $accessKeyId = $configModel::getConfigValue('ali_access_key');
            $accessKeySecret =  $configModel::getConfigValue('ali_secret_key');
            $endpoint = $configModel::getConfigValue('ali_domain');
            $bucket = $configModel::getConfigValue('ali_bucket');
            //实例化对象 将配置传入
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            //这里是有sha1加密 生成文件名 之后连接上后缀
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();
            //上传至阿里云的目录 为年+月/日的格式
            //执行阿里云上传 bucket名称,上传的目录,文件
            $result = $ossClient->uploadFile($bucket, $key, $files->getRealPath());

            //将结果输出
            return success('上传成功',['url'=>$result['info']['url']]);

        }
    }

    public function payAmount(){
        $payAmount  = new PayAmount();
        $list = $payAmount->where(['status' => 1])->select();
        $count=  $payAmount->where(['status' => 1])->count();
        return success('支付金额',['list'=> $list,'count' => $count]);
    }

    public function rollMessage(Request $request){
        $rollMessageModel = new RollMessage();
        $list = $rollMessageModel->select()->toArray();
        $count = $rollMessageModel->count();
        return success('滚动数据',['list'=> $list,'count' => $count]);

    }


    public function getAddress(Request $request){
        $param = $request->param();
        $longitude = number_format(doubleval($param['longitude']), 6);
        $latitude = number_format(doubleval($param['dimension']), 6);
        $gps = $latitude . ',' . $longitude;
        $params = array(
            'location' => $gps,
            'key' => Config::getConfigValue('tencent_map_key'),
        );
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
        $url = $url . '?' . http_build_query($params, '', '&');
        $mapResult = json_decode(curlGet($url));
        if ($mapResult->status == 0) {
            /* return error('百度地图数据获取有误')*/
            $user['province_name'] = $mapResult->result->address_component->province;
            $user['city_name'] = $mapResult->result->address_component->city;
            $user['area_name'] = $mapResult->result->address_component->district;
            $user['address'] = $mapResult->result->address;
        }else{
            return error('地址获取失败');
        }
        return success('地址',$user);
    }


}